package com.nowcoder.community.event;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName eventConsumer
 * @Description
 * @Author hhwu
 * @Date 2022/5/27 10:42
 * Version 1.0
 **/
@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})// 指定消费者监听的主题类型，监听到后会自动调用下面的方法进行处理.被动触发
    public void handleCommentMessage(ConsumerRecord record) {
        /**
         * @Author hhwu
         * @Description //TODO 消费点赞、关注、评论三种消息。监听到消息后会自动调用下面的方法进行处理.被动触发
         * TODO 本方法主要是监听点赞、关注、评论三种消息，然后将数据提交数据库，并向用户发送系统通知
         * @Date 14:52 2022/5/27
         * @Param [record]
         * @return void
         **/
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);// 将JSON格式字符串转回对象
        if (event == null) {
            logger.error("消息格式错误！");
        }

        // 发送站内通知。将消费者原始接受到到的事件转换为message数据库封装的对象
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        // 用于构建message中的content
        Map<Object, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        if (!event.getData().isEmpty()) {// 处理event中的其他数据
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }

    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        /**
         * @Author hhwu
         * @Description //TODO 消费发帖事件，将帖子传入es数据库
         * @Date 13:57 2022/5/30
         * @Param [record]
         * @return void
         **/
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);// 将JSON格式字符串转回对象
        if (event == null) {
            logger.error("消息格式错误！");
        }

        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());// 从数据库中查到帖子
        elasticsearchService.saveDiscussPost(post);// 将查到的帖子传入es数据库

    }

    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        /**
         * @Author hhwu
         * @Description //TODO 消费删帖事件，将es数据库中的帖子删除
         * @Date 13:57 2022/5/30
         * @Param [record]
         * @return void
         **/
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);// 将JSON格式字符串转回对象
        if (event == null) {
            logger.error("消息格式错误！");
        }

        elasticsearchService.deleteDiscussPost(event.getEntityId());
    }

    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShareMessage(ConsumerRecord record) {
        /**
         * @Author hhwu
         * @Description //TODO 消费分享事件，利用wk工具，将网页生成长图
         * @Date 22:14 2022/6/1
         * @Param [record]
         * @return void
         **/
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");

        // 生成长图的cmd命令
        String cmd = wkImageCommand + " --quality 75 " // 压缩比
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            Runtime.getRuntime().exec(cmd);
            logger.info("生成长图成功: " + cmd);
        } catch (IOException e) {
            logger.error("生成长图失败: " + e.getMessage());
        }
    }

}
